﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Psm.Session;
using Psm.Messaging;
using Psm.PubSub.Messaging;
using Psm.PubSub.StateCache;

namespace Psm.PubSub.Processors
{
    [PartCreationPolicy(CreationPolicy.NonShared)]
    [Export("CACHE_PROCESSOR_SUBSCRIPTION", typeof(IProcessor))]
    public class CacheSubscriptionProcessor : IProcessor
    {
        private static readonly string QUERIES = "QUERIES";

        public void ProcessMessage(ISession session, IMessage incoming)
        {
            QueryMessage message = incoming as QueryMessage;
            if( message != null )
            {
                GetSessionItem<List<QueryMessage>>(session, QUERIES).Add(message);
                TopicSpace space = StateCache.StateCache.Instance.GetTopicSpace(message.Topic);
                if (space != null)
                {
                    space.EvaluateQuery(session, message);
                }
            }
        }

        public void Intialize()
        {
            
        }

        public void NewSession(ISession session)
        {
            foreach (Schema schema in SchemaCollection.AllSchemas.Values)
            {
                session.SendMessage(new SchemaMessage(schema));
            }
            session.SendMessage(new SchemaMessage((Schema)null));
            session.Flush();

            session.State.Add(QUERIES, new List<QueryMessage>());
        }


        public void SessionClosed(ISession session)
        {
            //get each query and remove from topic
            foreach (QueryMessage message in GetSessionItem<List<QueryMessage>>(session, QUERIES))
            {
                TopicSpace space = StateCache.StateCache.Instance.GetTopicSpace(message.Topic);
                if (space != null)
                {
                    space.RemoveQuery(session, message);
                }
            }
        }


        public T GetSessionItem<T>(ISession session, string key)
        {
            return (T)session.State[key];
        }
    }
}
